console.log('buildChunk')
console.time('buildChunk')
require('../src/utils/Format');//日期
process.env.NODE_ENV='production';
const path = require('path');
const fs = require('fs-extra');
const glob = require('glob');
const mkdir = require('./utils/mkdir');
const getText = require('./utils/getText');
const makeChunk = require('./utils/makeChunk');
const crypto = require('crypto');

var cryptoMd5= function(password) {
  const md5 = crypto.createHash('md5');
  return md5.update(password).digest('hex');
};

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

/*
获取配置
* */
const Config=require('../config/app.config');
const historyVersion=resolve('historyVersion/')

/*
配置信息
打包目录:distPath
* */
const distPath=resolve(Config.path);
const curVersion=Config.curVersion;

/*
复制过去
* */
const curDateDir=path.join(historyVersion,curVersion);
if(!fs.existsSync(distPath)&&!fs.existsSync(curDateDir)){
  throw distPath+'目录不存在，请构建'
}
fs.emptyDirSync(distPath+'/chunk');
fs.emptyDirSync(curDateDir);
fs.copySync(distPath,curDateDir)

const versionList=fs.readdirSync(historyVersion);
versionList.sort(function (p1,p2) {
  return parseInt(p2)-parseInt(p1)
})
for(let i=0;i<versionList.length;i++){
  const preVersion=versionList[i];
  if(preVersion!==curVersion){
    const curDate=new Date(''+curVersion.replace(/(\d{2})(\d{2})(\d{2})/,'20$1-$2-$3'))
    const preDate=new Date(""+preVersion.replace(/(\d{2})(\d{2})(\d{2})/,'20$1-$2-$3'))
    const dayNum=(curDate.getTime()-preDate.getTime())/(1000*60*60*24);
    if(dayNum<60&&i<10){
      buildChunkBag(preVersion,curVersion)
    }else{
      fs.removeSync(path.join(historyVersion,preVersion));
    }
  }
}
//获取文件key
function getFileKey(url) {
  return url.replace(/(?!\w+)\.\w+\.(js|css)/,'.$1').replace(/\?.+/,'')
}
//搜索要打包的文件
function searchArr(dir) {
  const rdir=glob(dir,{sync:true})[0]+'/'
  const arr=glob(rdir+'**/*.?(js|css)',{
    sync:true
  }).map(function (filename) {
    return filename.replace(rdir,'')
  });
  return arr;
}

//数组转对象
function arrToMap(arr) {
  const obj={}
  arr.forEach(function (fpath) {
    const key=getFileKey(fpath)
    obj[key]=fpath;
  })
  delete obj['md5.js'];
  return obj;
}
//获取map
function getObjByVersion(version) {
  const arr=searchArr(historyVersion+version)
  const obj=arrToMap(arr)
 return obj;
}

//构建增量包
function buildChunkBag(preVersion,curVersion) {
  const chuankName=preVersion+'-'+curVersion+'.json'
  console.log('增量包',chuankName,'构建中')
  const preObj=getObjByVersion(preVersion)
  const curObj=getObjByVersion(curVersion)
  const arr=[]
  for(let name in curObj){
      if(curObj[name]!==preObj[name]&&preObj[name]){
        const s1=getText(path.join(historyVersion,preVersion,preObj[name]))
        const s2=getText(path.join(historyVersion,curVersion,curObj[name]))
        arr.push({
          a:preObj[name],
          b:curObj[name],
          c:makeChunk(s1,s2),
        })
      }
  }
  //输出增量包
  fs.outputJsonSync(path.join(historyVersion,curVersion,'chunk/',chuankName),arr)
  fs.outputJsonSync(path.join(distPath,'chunk/',chuankName),arr)
}
console.timeEnd('buildChunk')